package org.springblade.modules.restaurant.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.restaurant.entity.Task;
import org.springblade.modules.restaurant.entity.TaskRecord;
import org.springblade.modules.restaurant.enums.RestaurantRoleEnums;
import org.springblade.modules.restaurant.enums.TaskProgressStatusEnums;
import org.springblade.modules.restaurant.enums.TaskRecordStatusEnums;
import org.springblade.modules.restaurant.service.ITaskRecordService;
import org.springblade.modules.restaurant.service.ITaskService;
import org.springblade.modules.restaurant.vo.*;
import org.springblade.modules.restaurant.wrapper.TaskRecordWrapper;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/restaurant/taskrecord")
@Tag(name = "API - 任务记录")
public class ApiTaskRecordController {

	private ITaskRecordService taskRecordService;
	private ITaskService taskService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入taskRecord")
	public R<TaskRecordVO> detail(TaskRecord taskRecord) {
		TaskRecord detail = taskRecordService.getOne(Condition.getQueryWrapper(taskRecord));
		return R.data(TaskRecordWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 任务记录
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入taskRecord")
	public R<IPage<TaskRecordVO>> list(@ParameterObject TaskRecordVO taskRecord, @ParameterObject Query query) {

		BladeUser user = SecureUtil.getUser();
		if (user == null) {
			return R.fail("请求异常，请重新登录");
		}
		// 获取当前登录用户ID
		Long userId = user.getUserId();
		String role = user.getRoleName();
		String tenantId = user.getTenantId();
		log.info("当前登录用户ID:{},role:{},tenantId:{}", userId, role, tenantId);

		boolean isAdmin = RestaurantRoleEnums.ADMIN.getType().equals(role);
		LambdaQueryWrapper<TaskRecord> wrapper = Wrappers.lambdaQuery();

		Integer taskProgressStatus = taskRecord.getTaskProgressStatus();
		if (TaskProgressStatusEnums.EXPIRE.getCode().equals(taskProgressStatus)) {
			wrapper.in(TaskRecord::getStatus, TaskRecordStatusEnums.EXPIRE.getCode(), TaskRecordStatusEnums.NO_CHECK.getCode());
			wrapper.and(!isAdmin, w -> w.eq(TaskRecord::getUserId, userId).or().eq(TaskRecord::getInspectorId, userId));
		} else {
			wrapper.eq(TaskRecord::getStatus, taskProgressStatus);
			wrapper.and(!isAdmin, w -> w.eq(TaskRecord::getUserId, userId).or().eq(TaskRecord::getInspectorId, userId));
		}

		wrapper.eq(ObjUtil.isNotNull(taskRecord.getAreaId()), TaskRecord::getAreaId, taskRecord.getAreaId());
		wrapper.like(StrUtil.isNotBlank(taskRecord.getTaskName()), TaskRecord::getTaskName, taskRecord.getTaskName());
		wrapper.eq(ObjUtil.isNotNull(taskRecord.getTimeType()), TaskRecord::getTimeType, taskRecord.getTimeType());
		wrapper.orderByDesc(TaskRecord::getCreateTime);

		IPage<TaskRecord> pages = taskRecordService.page(Condition.getPage(query), wrapper);
		return R.data(TaskRecordWrapper.build().pageVO(pages));
	}

	/**
	 * 修改 任务记录
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入taskRecord")
	public R update(@Valid @RequestBody TaskRecord taskRecord) {
		// 任务提交  根据任务状态
		Integer status = taskRecord.getStatus();
		String deadline = taskRecord.getDeadline();
		if (TaskRecordStatusEnums.SUBMITTED.getCode().equals(status)) {
			// 是否已过截止日期
			if (StrUtil.isNotBlank(deadline) && DateUtil.parse(deadline).isBefore(DateUtil.date())) {
				return R.fail("任务已过截止日期");
			}
		}
		return R.status(taskRecordService.updateById(taskRecord));
	}

	// 设置执行人
	@PostMapping("/setExecutor")
	@Operation(summary = "设置执行人")
	public R setExecutor(@Valid @RequestBody TaskSetExecutorVO task) {
		return R.status(taskRecordService.setExecutor(task));
	}

	// 保存草稿
	@PostMapping("/saveDraft")
	@Operation(summary = "保存草稿")
	public R saveDraft(@Valid @RequestBody TaskDraftVO taskVO) {
		return R.status(taskRecordService.saveDraft(taskVO));
	}

	// 提交任务
	@PostMapping("/submitTask")
	@Operation(summary = "任务提交")
	public R submitTask(@Valid @RequestBody TaskSubmitVO taskVO) {
		return R.status(taskRecordService.submitTask(taskVO));
	}

	// 检查任务
	@PostMapping("/checkTask")
	@Operation(summary = "任务检查")
	public R checkTask(@Valid @RequestBody TaskCheckVO taskVO) {
		return R.status(taskRecordService.checkTask(taskVO));
	}

	// 驳回任务
	@PostMapping("/rejectTask")
	@Operation(summary = "任务驳回")
	public R rejectTask(@Valid @RequestBody TaskRejectVO taskVO) {
		return R.status(taskRecordService.rejectTask(taskVO));
	}

	// 任务评分
	@PostMapping("/scoreTask")
	@Operation(summary = "任务评分")
	public R scoreTask(@Valid @RequestBody TaskScoreVO taskVO) {
		return R.status(taskRecordService.scoreTask(taskVO));
	}

	// 新建任务并下发
	@PostMapping("/addTempTask")
	@Operation(summary = "新建任务并下发")
	public R addTempTask(@Valid @RequestBody TaskRecordVO task) {
		return R.status(taskRecordService.addTask(task));
	}

	// 任务下发
	@PostMapping("/assignTask")
	@Operation(summary = "任务下发")
	public R assignTask(@Valid @RequestBody TaskRecordVO taskVO) {
		Long taskId = taskVO.getTaskId();
		Task task = taskService.getById(taskId);
		return R.status(taskRecordService.assignTask(task, taskVO));
	}

	// 批量任务下发
	@PostMapping("/batchAssignTask")
	@Operation(summary = "批量任务下发")
	public R batchAssignTask(@Valid @RequestBody TaskRecordVO taskVO) {
		List<Long> taskIds = taskVO.getTaskIds();
		if (CollUtil.isEmpty(taskIds)) {
			return R.fail("任务ID不能为空");
		}
		for (Long taskId : taskIds) {
			Task task = taskService.getById(taskId);
			taskRecordService.assignTask(task, taskVO);
		}
		return R.success();
	}
}
